package com.chenjiajin.service.impl;

import com.chenjiajin.service.ITestService;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;

@Service
public class TestServiceImpl implements ITestService {

    @Override
    public void download(HttpServletResponse response) throws IOException {
        response.setContentType("application/pdf");
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("箱唛.pdf", "UTF-8"));

        // url地址 转化 为输入流
        //String urlStr = "https://gz-yuanmeng.oss-cn-guangzhou.aliyuncs.com/6a0f689a-2172-4223-aa5a-19d4882e2e45.pdf";
        //InputStream inputStream = new URL(urlStr).openStream();

        // 静态资源 转化为 输入流
        String tempPath = "pdf/模板.pdf";
        ClassPathResource resource = new ClassPathResource(tempPath);
        response.setHeader("Content-disposition", String.format("attachment; filename=%s", URLEncoder.encode(resource.getFilename(), "UTF-8")));
        response.addHeader("Content-Length", String.valueOf(resource.contentLength()));
        InputStream inputStream = resource.getInputStream();


        OutputStream outputStream = response.getOutputStream();
        FileCopyUtils.copy(inputStream, outputStream);

    }


}

